package com.naizhuai.ui.web;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.naizhuai.R;
import com.naizhuai.ui.components.swipeback.SwipeBackActivity;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.widget.Toast.makeText;

/**
 * @author：lichenxi
 * @date 2017/7/26 13
 * email：525603977@qq.com
 * Fighting
 */
public class WebActivity extends SwipeBackActivity implements ObservableWebView.OnScrollChangedListener {
    private static final String TAG = WebActivity.class.getSimpleName();

    private static final String EXTRA_URL = "extra_url";
    private static final String EXTRA_TITLE = "extra_title";

    private static final Map<String, Integer> URL_POSITION_CACHES = new HashMap<>();
    @BindView(R.id.title)
    TextView tooltitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.web_view)
    ObservableWebView webView;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    String url, title;
    int positionHolder;
    boolean overrideTitleEnabled = true;



    public static void start(Context context, String extraTitle, String extraURL) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra(EXTRA_TITLE, extraTitle);
        intent.putExtra(EXTRA_URL, extraURL);
        context.startActivity(intent);
    }

    /**
     * Using newIntent trick, return WebActivity Intent, to avoid `public static`
     * constant
     * variable everywhere
     *
     * @return Intent to start WebActivity
     */
    public static Intent newIntent(Context context, String extraTitle, String extraURL) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra(EXTRA_TITLE, extraTitle);
        intent.putExtra(EXTRA_URL, "http://im.yiyao365.cn/video/index.html");
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_web);
//        ButterKnife.bind(this);
        initToolbar();
        url = getIntent().getStringExtra(EXTRA_URL);
        title = getIntent().getStringExtra(EXTRA_TITLE);

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setAppCacheEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(true);
        settings.setDomStorageEnabled(true);
        webView.setWebChromeClient(new ChromeClient());
        webView.setWebViewClient(new ReloadableClient());
        webView.setOnScrollChangedListener(this);
        // webView.addJavascriptInterface(new JSInterface(), "JSInterface");

        webView.loadUrl(url);

//        textSwitcher.setFactory(() -> {
//            final Context context = WebActivity.this;
//            final TextView textView = new TextView(context);
//            textView.setTextAppearance(context, R.style.WebTitle);
//            textView.setSingleLine(true);
//            textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
//            textView.setOnClickListener(v -> v.setSelected(!v.isSelected()));
//            return textView;
//        });
//        textSwitcher.setInAnimation(this, android.R.anim.fade_in);
//        textSwitcher.setOutAnimation(this, android.R.anim.fade_out);
        if (title != null) setTitle(title);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }


    private void initToolbar() {
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            toolbar.setNavigationOnClickListener(view -> onBackPressed());
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayShowHomeEnabled(true);
                actionBar.setDisplayHomeAsUpEnabled(true);
                /* NOTE: Hide the origin title view */
                actionBar.setDisplayShowTitleEnabled(false);
            }
        } else {
            Log.e(TAG, "Toolbar == null");
        }
    }

    @Override public void setTitle(CharSequence str) {
        super.setTitle(title);
        if (tooltitle!=null)
            tooltitle.setText(str);
    }

    private class ChromeClient extends WebChromeClient {

        @Override public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (progressbar!=null){
                progressbar.setProgress(newProgress);
                if (newProgress == 100) {
                    progressbar.setVisibility(View.INVISIBLE);
                } else {
                    progressbar.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (overrideTitleEnabled) {
                setTitle(title);
            }
        }
    }

    private class ReloadableClient extends WebViewClient {

        @SuppressWarnings("deprecation")
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null) view.loadUrl(url);
            return true;
        }


        @Override public void onPageCommitVisible(WebView view, String url) {
            super.onPageCommitVisible(view, url);
            Integer _position = URL_POSITION_CACHES.get(url);
            int position = _position == null ? 0 : _position;
            view.scrollTo(0, position);
        }


//        @Override public void onPageFinished(WebView view, String url) {
//            super.onPageFinished(view, url);
//            boolean isBlackPage = false;
//            for (String blackKey : SwipeBlacklist.get()) {
//                if (url.contains(blackKey)) {
//                    isBlackPage = true;
//                    break;
//                }
//            }
//            if (isBlackPage) {
//                Toast.makeText(WebActivity.this,
//                        R.string.web_tip_swipe_back_disabled, Toast.LENGTH_LONG)
//                        .show();
//                swipeBackDelegate.setSwipeBackEnabled(false);
//            } else {
//                swipeBackDelegate.setSwipeBackEnabled(true);
//            }
//        }
    }
//    @Override
//    public int getLayoutId() {
//        return R.layout.activity_web;
//    }

    @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webView.canGoBack()) {
                        webView.goBack();
                    } else {
                        finish();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.web_menu_web, menu);
        return true;
    }

    @Override public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            refresh();
            return true;
        } else if (id == R.id.action_copy_url) {
            ClipBoards.copyToClipBoard(this, webView.getUrl());
            makeText(this, R.string.web_tip_copy_done, Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.action_open_url) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                makeText(this, R.string.web_tip_open_fail, Toast.LENGTH_LONG).show();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("deprecation")
    @Override protected void onDestroy() {
        final String url = webView.getUrl();
        int bottom = (int) Math.floor(webView.getContentHeight() * webView.getScale() * 0.8f);
        if (positionHolder >= bottom) {
            URL_POSITION_CACHES.remove(url);
        } else {
            URL_POSITION_CACHES.put(url, positionHolder);
        }
        super.onDestroy();
        if (webView != null) webView.destroy();
    }

    @Override
    public void onScrollChanged(WebView v, int x, int y, int oldX, int oldY) {
        positionHolder = y;
    }

    private void refresh() {
        webView.reload();
    }
}
